/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.dao.DAOException;
import org.mybeans.forms.FormBeanFactory;

import scheduler.databean.User;
import scheduler.formbean.SetPasswordForm;
import scheduler.model.BookmarkDao;
import scheduler.model.Model;
import scheduler.model.UserDao;


public class SetPasswordAction extends Action {
	private static FormBeanFactory<SetPasswordForm> formBeanFactory =
		FormBeanFactory.getInstance(SetPasswordForm.class,"<>\"");

	private UserDao  userDAO;
	private BookmarkDao bookmarkDao;

	public SetPasswordAction(Model model) {
		userDAO  = model.getUserDao();
		bookmarkDao = model.getBookmarkDao();
	}

	public String getName() { return "set-password.do"; }
    
    public String perform(HttpServletRequest request) {
        // Load the form parameters into a form bean
        SetPasswordForm form = formBeanFactory.create(request);
        
	    	// Set up error list
	        List<String> errors = new ArrayList<String>();
	        request.setAttribute("errors",errors);
	        request.setAttribute("form",form);
	        
	        // If no params were passed, return with no errors so that the form will be
	        // presented (we assume for the first time).
	        if (form.isEmpty()) {
	            return "set-password.jsp";
	        }

	        // Check for any validation errors
	        errors.addAll(form.getValidationErrors());
	        if (errors.size() != 0) {
	            return "set-password.jsp";
	        }

			User user = (User) request.getSession().getAttribute("user");
			// Change the password
			
	        try {
	        	if (!userDAO.checkPassword(user.getUserName(), form.getOldPassword())) {
	        		errors.add("Password is not correct.");
	        		return "set-password.jsp";
	        	}
	        	userDAO.setPassword(user.getUserName(),form.getNewPassword());

				user = userDAO.getUserByName(user.getUserName());
				
			} catch (DAOException e) {
				errors.add(e.getMessage());
				return "set-password.jsp";
			}

			request.setAttribute("message","Password changed for "+user.getUserName());
			try {
				request.setAttribute("bookmarks",bookmarkDao.getBookmarksForUser(user.getUserName()));

				request.setAttribute("registeredUsers", userDAO.getAll());
			} catch (DAOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
	        return "manage.jsp";
    }
}
